import { ref, computed } from 'vue'

// 拖拽操作类型枚举
export const DragOperationType = {
  ADD: 'add',
  MOVE: 'move',
  DELETE: 'delete',
  MODIFY: 'modify',
  REORDER: 'reorder'
} as const

export type DragOperationTypeValue = typeof DragOperationType[keyof typeof DragOperationType]

// 拖拽状态接口
export interface DragState {
  isDragging: boolean
  dragComponent: any
  dropTarget: any
  startPosition: { x: number; y: number }
  currentPosition: { x: number; y: number }
  dragType: 'new' | 'move' | 'resize'
}

// 拖拽指标接口
export interface DragMetrics {
  startTime: number
  endTime: number
  startPosition: { x: number; y: number }
  endPosition: { x: number; y: number }
  distance: number
  duration: number
  speed: number
}

// 拖拽历史接口
export interface DragHistory {
  operations: any[]
  currentIndex: number
  maxHistory: number
}

// 性能指标接口
export interface PerformanceMetrics {
  fps: number
  memoryUsage: number
  dragOperations: number
  renderTime: number
  lastUpdate: number
}

// 拖拽统计接口
export interface DragStatistics {
  totalOperations: number
  successfulOperations: number
  failedOperations: number
  successRate: number
  totalDragTime: number
  averageDragTime: number
  fastestDrag: number
  slowestDrag: number
  totalDragDistance: number
  averageDragDistance: number
  shortestDrag: number
  longestDrag: number
  averageDragSpeed: number
  fastestSpeed: number
  slowestSpeed: number
  operationTypeCounts: Record<DragOperationTypeValue, number>
  componentTypeCounts: Record<string, number>
  hourlyDistribution: number[]
  performanceTrends: {
    fps: number[]
    memoryUsage: number[]
    renderTime: number[]
  }
  userBehavior: {
    undoCount: number
    redoCount: number
    clearHistoryCount: number
    exportCount: number
    importCount: number
  }
}

// 工具函数

/**
 * 生成操作ID
 */
export const generateOperationId = (): string => {
  return `op_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

/**
 * 生成操作描述
 */
export const generateOperationDescription = (operation: any): string => {
  const { type, component, target } = operation
  const componentName = component?.name || component?.type || '未知组件'
  
  switch (type) {
    case DragOperationType.ADD:
      return `添加 ${componentName}`
    case DragOperationType.MOVE:
      return `移动 ${componentName}`
    case DragOperationType.DELETE:
      return `删除 ${componentName}`
    case DragOperationType.MODIFY:
      return `修改 ${componentName}`
    case DragOperationType.REORDER:
      return `重排序 ${componentName}`
    default:
      return `未知操作 ${componentName}`
  }
}

/**
 * 获取操作类型标签
 */
export const getOperationTypeLabel = (type: DragOperationTypeValue): string => {
  const labels = {
    [DragOperationType.ADD]: '添加',
    [DragOperationType.MOVE]: '移动',
    [DragOperationType.DELETE]: '删除',
    [DragOperationType.MODIFY]: '修改',
    [DragOperationType.REORDER]: '重排序'
  }
  return labels[type] || '未知'
}

/**
 * 格式化时间戳
 */
export const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

/**
 * 节流函数
 */
export const throttle = (func: Function, delay: number, key: string) => {
  const timers: Record<string, NodeJS.Timeout> = {}
  
  return (...args: any[]) => {
    if (timers[key]) {
      clearTimeout(timers[key])
    }
    
    timers[key] = setTimeout(() => {
      func.apply(null, args)
      delete timers[key]
    }, delay)
  }
}

/**
 * 清除节流定时器
 */
export const clearThrottleTimers = (timers: Record<string, NodeJS.Timeout>) => {
  Object.values(timers).forEach(timer => {
    if (timer) clearTimeout(timer)
  })
  Object.keys(timers).forEach(key => delete timers[key])
}

/**
 * 计算两点间距离
 */
export const calculateDistance = (start: { x: number; y: number }, end: { x: number; y: number }): number => {
  const dx = end.x - start.x
  const dy = end.y - start.y
  return Math.sqrt(dx * dx + dy * dy)
}

/**
 * 计算拖拽速度
 */
export const calculateSpeed = (distance: number, duration: number): number => {
  return duration > 0 ? distance / duration : 0
}

/**
 * 获取组件图标
 */
export const getWidgetIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    text: 'el-icon-document',
    button: 'el-icon-thumb',
    image: 'el-icon-picture',
    container: 'el-icon-folder',
    input: 'el-icon-edit',
    select: 'el-icon-arrow-down',
    checkbox: 'el-icon-check',
    radio: 'el-icon-circle-check'
  }
  return iconMap[type] || 'el-icon-component'
}

/**
 * 获取组件类型名称
 */
export const getComponentTypeName = (type: string): string => {
  const nameMap: Record<string, string> = {
    text: '文本组件',
    button: '按钮组件',
    image: '图片组件',
    container: '容器组件',
    input: '输入框组件',
    select: '选择器组件',
    checkbox: '复选框组件',
    radio: '单选框组件'
  }
  return nameMap[type] || '未知组件'
}

/**
 * 获取组件描述
 */
export const getComponentDescription = (component: any): string => {
  if (!component) return '未知组件'
  
  const { type, name, description } = component
  if (description) return description
  
  const defaultDescriptions: Record<string, string> = {
    text: '用于显示文本内容的组件',
    button: '可点击的按钮组件',
    image: '用于显示图片的组件',
    container: '可包含其他组件的容器',
    input: '用户输入文本的输入框',
    select: '下拉选择器组件',
    checkbox: '多选复选框组件',
    radio: '单选按钮组件'
  }
  
  return defaultDescriptions[type] || '组件描述'
}

/**
 * 检查组件是否为另一个组件的后代
 */
export const isDescendant = (targetComponent: any, dragComponent: any): boolean => {
  if (!targetComponent || !dragComponent) return false
  
  const checkChildren = (component: any, targetId: string): boolean => {
    if (!component.children) return false
    
    for (const child of component.children) {
      if (child.id === targetId) return true
      if (checkChildren(child, targetId)) return true
    }
    return false
  }
  
  return checkChildren(targetComponent, dragComponent.id)
}

/**
 * 获取组件层级
 */
export const getComponentLevel = (component: any): number => {
  if (!component) return 0
  
  let level = 0
  let current = component
  
  while (current.parent) {
    level++
    current = current.parent
  }
  
  return level
}

/**
 * 根据ID查找组件
 */
export const findComponentById = (id: string, components: any[]): any => {
  if (!id || !components) return null
  
  const findInArray = (arr: any[]): any => {
    for (const component of arr) {
      if (component.id === id) return component
      if (component.children) {
        const found = findInArray(component.children)
        if (found) return found
      }
    }
    return null
  }
  
  return findInArray(components)
}

/**
 * 检查目标组件是否可以接受拖拽
 */
export const canAcceptDrop = (targetComponent: any, dragComponent: any): boolean => {
  if (!targetComponent || !dragComponent) return false
  
  // 不能拖拽到自己
  if (targetComponent.id === dragComponent.id) return false
  
  // 不能拖拽到自己的后代
  if (isDescendant(targetComponent, dragComponent)) return false
  
  // 检查目标组件的接受类型
  const { acceptTypes = [] } = targetComponent
  if (acceptTypes.length > 0) {
    return acceptTypes.includes(dragComponent.type)
  }
  
  // 默认接受所有类型
  return true
}

/**
 * 计算放置评分
 */
export const calculateDropScore = (x: number, y: number, rect: DOMRect, component: any): number => {
  if (!rect || !component) return 0
  
  const centerX = rect.left + rect.width / 2
  const centerY = rect.top + rect.height / 2
  
  // 计算距离中心点的距离
  const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2)
  
  // 距离越近，评分越高
  const maxDistance = Math.max(rect.width, rect.height)
  const normalizedDistance = Math.min(distance / maxDistance, 1)
  
  // 基础评分
  let score = 1 - normalizedDistance
  
  // 根据组件类型调整评分
  if (component.type === 'container') {
    score *= 1.2 // 容器组件优先
  }
  
  return Math.max(0, Math.min(1, score))
}

/**
 * 查找最佳放置目标
 */
export const findBestDropTarget = (x: number, y: number, components: any[]): any => {
  if (!components || components.length === 0) return null
  
  let bestTarget = null
  let bestScore = 0
  
  const checkComponent = (component: any) => {
    if (!component.element) return
    
    const rect = component.element.getBoundingClientRect()
    if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
      const score = calculateDropScore(x, y, rect, component)
      if (score > bestScore) {
        bestScore = score
        bestTarget = component
      }
    }
    
    // 递归检查子组件
    if (component.children) {
      component.children.forEach(checkComponent)
    }
  }
  
  components.forEach(checkComponent)
  
  return bestTarget
}

/**
 * 生成组件HTML
 */
export const generateComponentHtml = (component: any): string => {
  if (!component) return ''
  
  const { type, props = {} } = component
  let html = ''
  
  switch (type) {
    case 'text':
      html = `<span>${props.text || '文本内容'}</span>`
      break
    case 'button':
      html = `<button>${props.text || '按钮'}</button>`
      break
    case 'image':
      html = `<img src="${props.src || ''}" alt="${props.alt || '图片'}" />`
      break
    case 'container':
      html = `<div class="container">${props.children?.map(generateComponentHtml).join('') || ''}</div>`
      break
    case 'input':
      html = `<input type="text" placeholder="${props.placeholder || '请输入'}" />`
      break
    case 'select':
      html = `<select><option>${props.options?.join('</option><option>') || '选项'}</option></select>`
      break
    default:
      html = `<div>${component.name || '组件'}</div>`
  }
  
  return html
}

/**
 * 获取FPS状态分类
 */
export const getFPSClass = (fps: number): string => {
  if (fps >= 55) return 'fps-excellent'
  if (fps >= 45) return 'fps-good'
  if (fps >= 30) return 'fps-fair'
  return 'fps-poor'
}

/**
 * 获取性能等级
 */
export const getPerformanceGrade = (fps: number): string => {
  if (fps >= 55) return 'A'
  if (fps >= 45) return 'B'
  if (fps >= 30) return 'C'
  return 'D'
}

/**
 * 获取性能等级文本
 */
export const getPerformanceGradeText = (grade: string): string => {
  const gradeTexts: Record<string, string> = {
    'A': '优秀',
    'B': '良好',
    'C': '一般',
    'D': '较差'
  }
  return gradeTexts[grade] || '未知'
}

/**
 * 获取性能建议
 */
export const getPerformanceSuggestions = (fps: number): string[] => {
  const suggestions: string[] = []
  
  if (fps < 30) {
    suggestions.push('性能较差，建议优化拖拽逻辑')
    suggestions.push('检查是否有不必要的DOM操作')
    suggestions.push('考虑使用虚拟滚动优化大量组件')
  } else if (fps < 45) {
    suggestions.push('性能一般，可以进一步优化')
    suggestions.push('减少拖拽过程中的实时计算')
    suggestions.push('优化事件监听器的绑定')
  } else if (fps < 55) {
    suggestions.push('性能良好，保持当前优化策略')
    suggestions.push('监控内存使用情况')
  } else {
    suggestions.push('性能优秀，继续保持')
  }
  
  return suggestions
}

/**
 * 获取推荐图标
 */
export const getRecommendationIcon = (type: string): string => {
  const iconMap: Record<string, string> = {
    warning: 'el-icon-warning',
    info: 'el-icon-info',
    success: 'el-icon-success'
  }
  return iconMap[type] || 'el-icon-info'
}

/**
 * 获取趋势条高度
 */
export const getTrendBarHeight = (fps: number): string => {
  const maxHeight = 60
  const height = Math.min((fps / 60) * maxHeight, maxHeight)
  return `${height}px`
}

/**
 * 获取趋势条样式类
 */
export const getTrendBarClass = (fps: number): string => {
  if (fps >= 55) return 'trend-excellent'
  if (fps >= 45) return 'trend-good'
  if (fps >= 30) return 'trend-fair'
  return 'trend-poor'
}

/**
 * 获取柱状图高度
 */
export const getBarHeight = (count: number, maxCount: number): string => {
  const maxHeight = 100
  const height = maxCount > 0 ? (count / maxCount) * maxHeight : 0
  return `${height}px`
}

/**
 * 获取小时分布柱状图高度
 */
export const getHourlyBarHeight = (count: number, maxCount: number): string => {
  const maxHeight = 80
  const height = maxCount > 0 ? (count / maxCount) * maxHeight : 0
  return `${height}px`
}
